<script lang="ts" setup>
import { computed } from 'vue';

import { MdiEdit } from '@vben/icons';
import { preferences, usePreferences } from '@vben/preferences';

import { Button, Divider, Radio, RadioGroup, Select } from 'ant-design-vue';
import dayjs from 'dayjs';

const props = defineProps({
  form: {
    type: Object,
    default: () => ({}),
  },
  editStatus: {
    type: Object,
    default: () => ({}),
  },
});
const emit = defineEmits([
  'update:form',
  'update:editStatus',
  'init',
  'submit',
]);

const formData = computed({
  get() {
    return props.form;
  },
  set(newValue) {
    emit('update:form', newValue);
  },
});

const edit = computed({
  get() {
    return props.editStatus;
  },
  set(newValue) {
    emit('update:editStatus', newValue);
  },
});

// 用计算属性监听早餐开始时间与结束时间是否相隔一小时以上，以及结束时间必须大于开始时间 使用dayjs
const isBreakfastTimeValid = computed(() => {
  const start = dayjs(formData.value.breakfastStart, 'HH:mm:ss');
  const end = dayjs(formData.value.breakfastEnd, 'HH:mm:ss');
  // 计算结束时间与开始时间的差值（单位：小时）
  const diffHours = end.diff(start, 'hour', true);
  // 判断结束时间是否大于开始时间，且间隔至少一小时
  return end.isAfter(start) && diffHours >= 1;
});

// 早餐形式 1=自助餐 2=套餐 3=单点'
const breakfastTypeRadio = [
  {
    value: 1,
    label: '自助餐',
  },
  {
    value: 2,
    label: '套餐',
  },
  {
    value: 3,
    label: '单点',
  },
];

// 早餐开始时间
const startTimeList = Array.from({ length: 29 }, (_, i) => {
  const hour = Math.floor(i / 2);
  const minute = i % 2 === 0 ? '00:00' : '30:00';
  return {
    value: `${hour < 10 ? '0' : ''}${hour}:${minute}`,
    label: `${hour < 10 ? '0' : ''}${hour}:${minute}`,
  };
});

// 通知父组件初始化一些接口
const init = () => {
  emit('init');
};

// 取消编辑事件
const cancelEdit = (key: string) => {
  edit.value[key] = false;
  init();
};

// 打开编辑事件 并关闭其他的编辑状态
const openEdit = (key: string) => {
  edit.value[key] = true;
  Object.keys(edit.value).forEach((item) => {
    if (item !== key && edit.value[item]) {
      cancelEdit(item);
    }
  });
};

const submit = async () => {
  if (!isBreakfastTimeValid.value) {
    return;
  }
  emit('submit', 'mealPolicy');
};

// 使用 usePreferences 函数获取主题相关信息
const { isDark } = usePreferences();

// 计算当前主题
const currentTheme = computed(() => {
  if (preferences.theme.mode === 'auto') {
    return isDark.value ? 'dark' : 'light';
  }
  return preferences.theme.mode;
});

// 触发单选事件
const radioChange = (e: any, key: keyof typeof formData.value) => {
  formData.value[key] = e.target.value;
};
</script>

<template>
  <div>
    <div v-if="!edit.mealPolicy" class="px-4 pb-6">
      <div class="flex items-center justify-between py-1">
        <div class="text-xl font-bold">早餐信息</div>
        <div>
          <Button
            class="flex h-auto items-center px-0 py-3"
            type="link"
            @click="openEdit('mealPolicy')"
          >
            <template #icon>
              <MdiEdit class="icon mr-1" />
            </template>
            编辑
          </Button>
        </div>
      </div>
      <div>
        <div class="text-xl">是否提供早餐</div>
        <div>
          {{ formData.isBreakfast ? '提供' : '不提供' }}
        </div>
      </div>
      <Divider />
      <div>
        <div class="text-xl">形式</div>
        <div>
          {{
            breakfastTypeRadio.find(
              (item) => item.value === formData.breakfastType,
            )?.label || '暂无'
          }}
        </div>
      </div>
      <Divider />
      <div>
        <div class="text-xl">早餐时间</div>
        <div>
          每日{{
            formData.breakfastStart
              ? dayjs(formData.breakfastStart, 'HH:mm:ss').format('HH:mm')
              : '请设置'
          }}
          至
          {{
            formData.breakfastEnd
              ? dayjs(formData.breakfastEnd, 'HH:mm:ss').format('HH:mm')
              : '请设置'
          }}
        </div>
      </div>
    </div>
    <div v-else class="px-4 pb-6">
      <div
        class="card-box sticky top-[-21px] z-[10] flex items-center justify-between rounded-none border-none py-4"
      >
        <div class="text-xl font-bold">早餐信息</div>
        <div class="flex items-center">
          <Button
            class="flex h-auto items-center px-5 py-2"
            @click="cancelEdit('mealPolicy')"
          >
            取消
          </Button>
          <Button
            class="ml-2 flex h-auto items-center px-5 py-2"
            type="primary"
            @click="submit"
          >
            保存
          </Button>
        </div>
      </div>
      <div>
        <div class="text-xl">是否提供早餐</div>
        <div class="pt-2">
          <RadioGroup
            :value="formData.isBreakfast"
            @change="radioChange($event, 'isBreakfast')"
          >
            <div class="relative py-1">
              <Radio :class="[currentTheme]" :value="true"> 提供 </Radio>
            </div>
            <div class="relative py-1">
              <Radio :class="[currentTheme]" :value="false"> 不提供 </Radio>
            </div>
          </RadioGroup>
        </div>
      </div>
      <Divider />
      <div>
        <div class="text-xl">形式</div>
        <div class="pt-2">
          <RadioGroup
            :value="formData.breakfastType"
            @change="radioChange($event, 'breakfastType')"
          >
            <div
              v-for="item in breakfastTypeRadio"
              :key="item.value"
              class="relative py-1"
            >
              <Radio :class="[currentTheme]" :value="item.value">
                {{ item.label }}
              </Radio>
            </div>
          </RadioGroup>
        </div>
      </div>
      <Divider />
      <div>
        <div class="text-xl">早餐时间</div>
        <div class="text-sm text-gray-500">设置每日的早餐时间</div>
        <div class="flex items-center pt-2">
          <Select
            v-model:value="formData.breakfastStart"
            :options="startTimeList"
            size="large"
            style="width: 120px"
          />
          <span class="mx-2">-</span>
          <Select
            v-model:value="formData.breakfastEnd"
            :options="startTimeList"
            size="large"
            style="width: 120px"
          />
        </div>
        <div class="pt-1 text-sm text-red-500">
          {{
            !isBreakfastTimeValid
              ? '早餐结束时间和开始时间至少间隔一个小时并结束时间大于开始时间'
              : ''
          }}
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.icon {
  color: hsl(var(--primary));
}

.light {
  color: hsl(var(--card-foreground));
}
</style>
